<!DOCTYPE html>
<html>
<head>
	<title>碰撞</title>
</head>
<body>

	<canvas id="canvas"></canvas>
	<script type="text/javascript">
		var canvas=document.getElementById("canvas");
		var ctx=canvas.getContext("2d");

		var width=400,height=300;
		canvas.width=width;
		canvas.height=height;
		canvas.style.border="1px solid #ff00ff";


		var x=0;
		var y=0;
		var xTag=true;
		var yTag=true;
		var step=1;

		setInterval(()=>{
			ctx.clearRect(x,y,50,50)
			
			
			if(x>width-50){
				xTag=false;
			}
			if(x<0){
				xTag=true;
			}

			if(y>height-50){
				yTag=false;
			}
			
			if(y<0){
				yTag=true;
			}

			if(xTag){
				x+=step;
			}else{
				x-=step
			}

			if(yTag){
				y+=step
			}else{
				y-=step
			}
			ctx.fillStyle="#ff0000";
			ctx.fillRect(x,y,50,50);
		},10)


	</script>
</body>
</html>